from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from rest_framework.response import Response

from apps.meiduo_admin.serializers.statistical import GoodsSerializer
from apps.users.models import User
from datetime import date
from apps.orders.models import OrderInfo
from datetime import timedelta
from apps.goods.models import GoodsVisitCount
from rest_framework.generics import ListAPIView


# 1.统计用户总数
class TotalView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 统计用户总数
        total = User.objects.filter(is_staff=False).count()

        return Response({
            'count': total,
            'date': date.today()
        })


# 2.日增用户统计
class DayView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        today = date.today()

        count = User.objects.filter(is_staff=False, date_joined__gte=today).count()

        return Response({
            'count': count,
            'date': today
        })


# 3.日活跃用户统计
class ActiveView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        today = date.today()

        # last_login记录最后的登录时间
        count = User.objects.filter(is_staff=False, last_login__gte=today).count()
        return Response({
            'count': count,
            'date': today
        })


# 4.日下单用户统计
class OrderView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        today = date.today()

        count = User.objects.filter(orders__create_time__gte=today).distinct().count()

        return Response({
            'count': count,
            'date': today
        })


# 5.月增用户统计
class MonthView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 统计一个月内（30天）,每天新增加的用户
        today = date.today()

        count_list = []

        for i in range(29, -1, -1):
            # 计算一个月内某天的开始时间
            day_begin = today - timedelta(days=i)
            # 计算一个月内某天的结束时间
            day_end = day_begin + timedelta(days=1)
            # 查询某天内注册的用户数量
            day_count = User.objects.filter(is_staff=False, date_joined__gte=day_begin, date_joined__lt=day_end).count()
            # 加入列表
            count_list.append({
                'date': day_begin,
                'count': day_count
            })
        return Response(count_list)


# 6.日分类商品访问量
class GoodsView(ListAPIView):
    # 查询今天所有的第三级访问量
    queryset = GoodsVisitCount.objects.filter(date=date.today())
    # 通过序列化器将访问量转化位字典
    serializer_class = GoodsSerializer
